<template>
  <!-- 角色表单弹窗 -->
  <a-modal
    v-model:open="localVisible"
    :title="modalTitle"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitLoading"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
    >
      <a-form-item label="角色名称" name="name" required>
        <a-input v-model:value="formState.name" placeholder="请输入角色名称" />
      </a-form-item>
      <a-form-item label="角色编码" name="code" required>
        <a-input
          v-model:value="formState.code"
          placeholder="请输入角色编码"
          :disabled=" formState.id && formState.id !== null"
        />
      </a-form-item>
      <a-form-item label="角色描述" name="description">
        <a-textarea
          v-model:value="formState.description"
          placeholder="请输入角色描述"
          :rows="4"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
const props = defineProps({
  modalTitle: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  },
  formState: {
    type: Object,
    default: () => ({})
  },
});
const emit = defineEmits(['update:visible', 'submit', 'cancel']);
// 创建本地表单ref引用
const formRef = ref(null);
// 使用计算属性代理visible属性
const localVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});
// 动态表单验证规则
const rules = computed(() => ({
  name: [{ required: true, message: '请输入角色名称' }],
  code: [{ required: true, message: '请输入角色编码' }],
}));
// 加载状态
const submitLoading = computed(() => props.loading);
// 提交表单
const handleSubmit = () => {
  console.log('submitData',{...props.formState})
  formRef.value?.validate().then(() => {
    const submitData = { ...props.formState };
    // 如果是编辑模式且密码为空，删除密码字段
    if (submitData.id && !submitData.password) {
      delete submitData.password;
    }
    emit('submit', submitData);
  }).catch(err => {
    console.error('表单验证失败:', err);
  });
};

// 取消操作
const handleCancel = () => {
  // resetForm();
  emit('cancel');
};

// 重置表单
const resetFields = () => {
  formRef.value?.resetFields();
};
onMounted(() => {
  
})
</script>

